package com.appkubes.fintech.restful.application.pay.wechat;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.appkubes.fintech.common.response.Response;
import com.appkubes.fintech.restful.application.pay.common.contract.response.PayModelResponse;
import com.appkubes.fintech.restful.application.pay.enums.WeChatPayEnums;
import com.appkubes.fintech.restful.application.pay.wechat.config.WeChatConfig;
import com.appkubes.fintech.restful.application.pay.wechat.request.PayRequest;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component("weChatCore")
public class WeChatCore {

    @Value("${pay.wechat.appid}")
    private String appId;
    @Value("${pay.wechat.appid2}")
    private String appId2;
    @Value("${pay.wechat.merchid}")
    private String merchId;
    @Value("${pay.wechat.wxkey}")
    private String privateKey;

    /**
     * @description: 处理通知回调参数
     * @author: xqc
     * @date: 2019/12/27 16:04
     * @params:
     * @return:
     */
    public Response notifyParasm(HttpServletRequest request)throws  Exception{
        InputStream inputStream  = request.getInputStream();
        int contentLength = request.getContentLength();
        if (contentLength < 0 || contentLength >= 4 * 1024 * 1024) {  // 请求数据大于4M 返回异常
            return Response.fail("数据过大");
        }
        //获取参数
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        IOUtils.copy(inputStream, bos, contentLength);
        byte[] bufer = bos.toByteArray();
        String xmlBuffer = new String(bufer, WeChatPayConstant.UTF8);
        Map<String, String> notifyMap = WXPayUtil.xmlToMap(xmlBuffer);
        return Response.success(notifyMap);
    }


    /**
     * @description: h5支付返回给客户端参数
     * @author: xqc
     * @date: 2019/12/27 15:53
     * @params:
     * @return:
     */
    public PayModelResponse payRetH5(PayModelResponse payModelResponse, Map<String,String> resp,PayRequest payRequest)throws Exception{
        String mweb_url = resp.get(WeChatPayConstant.PAY_H5_RET_URL) + "&redirect_url=" + URLEncoder.encode(payRequest.getBackUrl(), "UTF-8");

        log.info("微信H5支付 = {}", mweb_url);
        payModelResponse.setPayData(mweb_url);
        payModelResponse.setRetType("url");
        return payModelResponse;
    }
    /**
     * @description: 组装微信PAY
     * @author: xqc
     * @date: 2019/12/27 15:38
     * @params:
     * @return:
     */
    public WXPay makePay( WeChatPayEnums payEnums){
        WeChatConfig weChatConfig = new WeChatConfig(appId, merchId, privateKey);
        WXPay wxpay = new WXPay(weChatConfig);
        return wxpay;
    }


    /**
     * @description: APP支付返回给客户的参数
     * @author: xqc
     * @date: 2019/12/27 15:53
     * @params:
     * @return:
     */
    public PayModelResponse payRetApp(PayModelResponse payModelResponse,Map<String,String> resp)throws Exception{
        Map<String, String> params = new HashMap<String, String>();
        params.put("appid", appId);  //app支付用的加密的appId不同
        params.put("partnerid", merchId);
        params.put("prepayid", resp.get("prepay_id"));
        params.put("noncestr", WXPayUtil.generateNonceStr());
        params.put("timestamp", System.currentTimeMillis() / 1000 + "");
        params.put("package", "Sign=WXPay");
        String sign = WXPayUtil.generateSignature(params, privateKey);
        params.put("sign", sign);
        log.info("微信APP支付{}", JSON.toJSONString(params));
        payModelResponse.setRetType("url");
        payModelResponse.setPayData(JSON.toJSONString(params));
        return payModelResponse;
    }
    /**
     * @description:  生成通用微信配置参数
     * @author: xqc
     * @date: 2019/12/27 15:35
     * @params:
     * @return:
     */
    public Map<String,String> makeRequestParams(WeChatPayEnums payEnums, PayRequest payRequest){
        Map<String, String> data = new HashMap<String, String>();
        data.put("body",payRequest.getBody());
        data.put("out_trade_no", payRequest.getOrderNo());
        data.put("fee_type", "CNY");
        data.put("total_fee", payRequest.getPayAmt().toString()); //    微信1表示1分钱
        data.put("spbill_create_ip", payRequest.getIp());
        data.put("notify_url", payRequest.getNotifyUrl());
        data.put("trade_type", payEnums.getValue());
        if(payEnums.getValue().equals (WeChatPayEnums.NATIVE.getValue ())){   // NATIVE需要设置过期时间
            int timeMim = 120 *1000;  //配置中心的是秒要转成毫秒
            data.put("time_expire", DateUtil.format (DateUtil.date(System.currentTimeMillis()+timeMim),"yyyyMMddHHmmss"));
        }

        if(payEnums.getValue().equals (WeChatPayEnums.MWEB.getValue ())){  // 微信H5支付scene_info必传
            data.put("scene_info", "{\"h5_info\": {\"type\":\"Android\",\"app_name\": \"game\",\"package_name\": \""+payRequest.getSubJect()+"\"}}");
        }
        log.info("微信支付 data = {} ", data);
        return data;
    }
}
